package se.topshelf.golftracker.web.controller.hole;

import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import se.topshelf.golftracker.core.domain.Course;
import se.topshelf.golftracker.core.domain.Hole;
import se.topshelf.golftracker.core.service.BaseService;
import se.topshelf.golftracker.core.service.CourseService;
import se.topshelf.golftracker.web.controller.BaseEntityController;
import se.topshelf.golftracker.web.editor.BaseEntityEditor;

import javax.annotation.Resource;

/**
 *
 */
@Controller
@SessionAttributes("entity")
@RequestMapping("/hole")
public class HoleController extends BaseEntityController<Hole> {
    public static final String HOLE_CONTEXT_PATH = "hole";
    @Resource  // Automatically set ("wired") by Spring
    private CourseService courseService;
    private static final String COURSE_MODEL_ATTRIBUTE = "course";

    public HoleController() {
        super(Hole.class);
    }

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        binder.registerCustomEditor(Course.class, "course", new BaseEntityEditor<Course>(Course.class, courseService));
    }

    @Override
    protected void doAddParentToModel(ModelMap model, String parentId) {
        Course course = courseService.get(parentId);
        if(course != null) {
            model.addAttribute(COURSE_MODEL_ATTRIBUTE, course);
        } else{
            throw new IllegalArgumentException("Tried to create a new hole without attaching it to a Course");
        }
    }


    @Override
    protected void doSave(Hole entityToSave) {
        courseService.saveOrUpdate(entityToSave);
    }

    @Override
    protected String getRedirectAfterSavePath(Hole savedHole) {
        // ToDo What if more than one course. Which to re-direct to
        return "redirect:" + "/course/view.htm?id=" + savedHole.getCourse().getId();
    }

    @Override
    protected Validator getValidator() {
        return new HoleValidator(courseService);
    }

    @Override
    protected String getEntityUrlContextPath() {
        return HOLE_CONTEXT_PATH;
    }

    @Override
    protected BaseService getBaseService() {
        return courseService;
    }

    @Override
    protected void addModelReferenceData(ModelMap model, Hole entity) {
        if (entity.getCourse() != null) {
            model.put(COURSE_MODEL_ATTRIBUTE, entity.getCourse());
        }
    }
}
